package battleship;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class NewRunningGamesServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // add a game to the lobby when it starts being played (two users start a new game or two users return to a game)
        System.out.println("NewRunningGamesServlet: starting");
    	String userToken= request.getParameter("token");
    	int id= (Integer) UserIdTokenHashMap.idTokenMap.get(userToken);
       // int id = Integer.parseInt(request.getParameter("id"));
        User user = Context.users[id];

        Game game = new Game();
        try {
            game = user.newRunningGames.take();
            if (!user.online) {
                return;
            }
        } catch (InterruptedException e) {
            System.out.println("NewRunningGamesServlet InterruptedException: " + e.getMessage());
        }
        int player1ID = game.player1ID;
        User player1 = Context.users[player1ID];
        String username1 = player1.username;
        int player2ID = game.player2ID;
        User player2 = Context.users[player2ID];
        String username2 = player2.username;

        // json
        String reply = " { \"id1\": \"" + player1ID + "\", \"username1\": \"" + username1 + "\", " +
                "\"id2\": \"" + player2ID + "\", \"username2\": \"" + username2 + "\" } ";

        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print(reply);
        out.close();
        System.out.println("newRunningGamesServlet: " + reply);
        System.out.println("NewRunningGamesServlet: finished");
    }
}
